<template>
    <div class="esl">
        <div class="user-data" v-if="!circulationVisible">
            <div class="public-filter">
                <div style="display: flex">
                    <custom-filter
                        :selectMerchant="selectMerchant"
                        :selectCurMerchant="selectCurMerchant"
                        @onSubmit="handleInitQuery"
                        @onSelect="handleSelectQuery"
                    ></custom-filter>
                </div>

                <div style="display: flex">
                    <div class="public-filter-item" v-if="userType == 'D'">
                        <a-button type="primary" @click="handDevice">下载设备表</a-button>
                    </div>
                    <div class="public-filter-item" v-if="userType == 'T' || userType == 'D'">
                        <a-button type="primary" @click="handlePaw">导出心跳表</a-button>
                    </div>

                    <div class="public-filter-item" v-if="userType == 's'"><a-button type="primary">批量转库</a-button></div>
                    <div class="public-filter-item" v-if="userType == 'A' || userType == 's'">
                        <a-button type="primary" @click="handBinding">下载绑定关系表</a-button>
                    </div>
                    <div class="public-filter-item" v-if="userType == 'A' || userType == 's'">
                        <a-button type="primary" @click="handleImport">批量修改型号</a-button>
                    </div>
                </div>
            </div>
            <div class="user-data__table">
                <a-table
                    :columns="columnsList"
                    :data-source="dataSource"
                    :pagination="pagination"
                    @change="handleTableChange"
                    :row-key="setRowKey"
                >
                    <template v-for="item in columnsList" :key="item.dataIndex" v-slot:[item.slotName]>
                        <span>{{ t(`yl.${item.slotName}`) }}</span>
                    </template>
                    <template #online="{ record }">
                        <span>{{ record.online == true ? t('yl.online') : t('yl.offline') }}</span>
                    </template>
                    <template #customAction="{ record }">
                        <a-button
                            class="action-btn"
                            v-if="userType == 's' || userType == 'A'"
                            @click="handleEdit(record)"
                            type="primary"
                            size="small"
                        >
                            <template #icon>
                                <EditOutlined />
                            </template>
                        </a-button>
                        <a-button
                            class="action-btn"
                            v-if="userType == 's'"
                            type="danger"
                            size="small"
                            @click="handCirculation(record)"
                        >
                            <template #icon>
                                <FieldTimeOutlined />
                            </template>
                        </a-button>
                        <a-button
                            class="action-btn"
                            v-if="userType == 's' || userType == 'A'"
                            type="danger"
                            size="small"
                            @click.stop="handHeartbeat(record)"
                        >
                            <template #icon>
                                <HeartOutlined />
                            </template>
                        </a-button>
                        <a-button class="action-btn" type="danger" size="small" @click.stop="handissue(record)">
                            <template #icon>
                                <MenuOutlined />
                            </template>
                        </a-button>
                    </template>
                </a-table>
            </div>
        </div>
        <yl-dept-model
            :visible="visible"
            :loading="confirmLoading"
            :title="title"
            :selectEditModel="selectModels"
            :dept="selectedRow"
            @cancle="handleCancle"
            @submit="handleSubmit"
        ></yl-dept-model>
        <circulationRecord
            :visible="circulationVisible"
            :loading="confirmLoading"
            :dept="circulationSelectedRow"
            @cancle="circulationHandleCancle"
        ></circulationRecord>
        <heartbeatModel
            :visible="HeartbeatVisible"
            :loading="confirmLoading"
            :dept="selectedRow"
            @cancle="heartbeathandleCancle"
        ></heartbeatModel>
        <distributionModel
            :visible="issueVisible"
            :loading="confirmLoading"
            :dept="distributionselectedRow"
            @cancle="distributionHandleCancle"
        ></distributionModel>
        <binding-model
            :visible="bindingShow"
            :loading="confirmLoading"
            :selectMerchant="selectMerchant"
            :selectCurMerchant="selectCurMerchant"
            @cancle="handleBindingCancle"
            @submit="handleBindingSubmit"
        ></binding-model>
        <importModel
            :visible="importVisible"
            :loading="importLoading"
            :title="importTitle"
            @cancle="handleImportCancle"
            @submit="handleimportSubmit"
        ></importModel>

        <yl-paw-model
            :visible="pawVisible"
            :loading="pawLoading"
            :title="pawTitle"
            :pawId="pawId"
            :notesTitle="notesTitle"
            :type="type"
            :userType="userType"
            :password="password"
            @cancle="handlePawCancle"
            @submit="handlePawSubmit"
        ></yl-paw-model>
        <dev-model :visible="devShow" @cancle="handDevCancle" @submit="handDevSubmit"></dev-model>
    </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, computed, onUnmounted, reactive, toRefs, ref, watch } from 'vue';
import { FieldTimeOutlined, HeartOutlined, MenuOutlined } from '@ant-design/icons-vue';
import circulationRecord from '@/components/circulationRecord/circulationModel.vue';
import heartbeatModel from '@/components/heartbeat/heartbeatModel.vue';
import ylMultiButton from '@/components/ylMultiButton.vue';
import distributionModel from '@/components/distribution/distributionModel.vue';
import ylPawModel from './components/pawModel.vue';
import customFilter from './components/tableFilter.vue';
import ylDeptModel from './components/deptModel.vue';
import bindingModel from './components/bindingModel.vue';
import devModel from './components/dev/devModel.vue';
import importModel from '@/components/importModel.vue';
import { useI18n } from 'vue-i18n';
import columns from './eslColumns';
import eslTables from './eslTables';
import { putheartbeat } from '@/api/device';

//import useDeleteUser from './deleteUser';
import { message } from 'ant-design-vue';
import { filter } from 'lodash';
interface State {
    title: string;
    confirmLoading: boolean;
}

export default defineComponent({
    name: 'user',
    components: {
        ylMultiButton,
        customFilter,
        FieldTimeOutlined,
        HeartOutlined,
        MenuOutlined,
        circulationRecord,
        ylDeptModel,
        heartbeatModel,
        distributionModel,
        bindingModel,
        importModel,
        ylPawModel,
        devModel,
    },

    setup() {
        const { t } = useI18n();
        const userType = localStorage.getItem('userType') ? localStorage.getItem('userType') : '';
        let {
            tableQuery,
            getHeartbeatData,
            merchantData,
            getCurMerchantData,
            getStoreData,
            getModelData,
            systypeQuery,
            selectedRow,
            merchantQuery,
            modelQuery,
            visible,
            circulationVisible,
        } = eslTables;
        const columnsList = ref<NormalObj[]>([]);
        const state: State = reactive({
            title: computed(() => (JSON.stringify(selectedRow) !== '{}' ? t('yl.editDeviceType') : t('yl.addUser'))),
            confirmLoading: false,
        });

        const bindingShow = ref(false);
        const importModel = reactive({
            importVisible: false,
            importLoading: false, // 弹窗按钮的loading
            importTitle: '批量修改型号',
        });
        const paw = reactive({
            pawVisible: false,
            pawLoading: false, // 弹窗按钮的loading
            pawTitle: '冻结商户',
            pawId: '',
            notesTitle: '注：冻结后该商户无法使用',
            type: '1',
            password: '',
        });

        const devShow = ref(false);
        onMounted(async () => {
            initFun();
            getHeartbeatData(tableQuery);
            if (localStorage.getItem('userType') == 's' || localStorage.getItem('userType') == 'A') {
                getCurMerchantData(systypeQuery); //所有的商户
            } else {
                getStoreData();
            }
            getModelData(modelQuery); //所有的型号
        });
        onUnmounted(() => {
            circulationVisible.value = false;
        });
        // 查询当前用户类型 (s: 系统; A: 渠道代理; T: 商户; D: 门店)
        const initFun = () => {
            switch (userType) {
                case 'T':
                    const merchant = [
                        'eslUseStore',
                        'eslMerchan',
                        'eslTemplate',
                        'eslMerchanCode',
                        'eslMerchanName',
                        'eslBelongingMerchan',
                    ];
                    tableHeadFun(merchant);
                    break;
                case 's':
                    const operate = ['elsStore', 'eslBelongingMerchan'];
                    tableHeadFun(operate);
                    break;
                case 'A':
                    const agent = ['eslMerchan', 'elsStore'];
                    tableHeadFun(agent);
                    break;
                default:
                    const store = [
                        'eslBelongingMerchan',
                        'eslUseStore',
                        'eslMerchan',
                        'eslTemplate',
                        'eslMerchanCode',
                        'eslMerchanName',
                        'elsStore',
                    ];
                    tableHeadFun(store);
                    break;
            }
        };

        // 初始化表格显示数据
        const tableHeadFun = (list: any) => {
            columnsList.value = columns.filter(function (item: any, index) {
                return list.indexOf(item.slotName) == -1;
            });
        };
        // 设置table row key
        const setRowKey = (record: { [x: string]: any }) => record.deviceCode;
        // 根据商户获取所有的门店;
        const handleSelectQuery = (query: any) => {
            console.log(merchantQuery);
            merchantQuery.parentCode = query.curMerchantCode;
            merchantData(merchantQuery);
        };
        // 初始化搜索
        const handleInitQuery = (query: any) => {
            tableQuery.page = 0;
            tableQuery = Object.assign({}, tableQuery, { ...query });
            getHeartbeatData(tableQuery);
        };
        // 隐藏弹窗
        const handleCancle = () => {
            visible.value = false;
        };
        // 新增、编辑
        const handleSubmit = (dept: NormalObj) => {
            state.confirmLoading = true;
            const msg = dept.id ? t('yl.editSuccess') : t('yl.addSuccess');
            const realRequest = dept.id ? putheartbeat(dept) : putheartbeat(dept);
            return realRequest
                .then(() => {
                    state.confirmLoading = false;
                    message.success(msg);
                    visible.value = false;
                    const timer = setTimeout(() => {
                        getHeartbeatData(tableQuery);
                        clearTimeout(timer);
                    }, 500);
                })
                .catch(() => {
                    state.confirmLoading = false;
                });
        };
        //
        const handBinding = () => {
            bindingShow.value = true;
        };
        const handleBindingCancle = () => {
            bindingShow.value = false;
        };
        const handleBindingSubmit = () => {
            bindingShow.value = false;
        };
        // 批量导入
        const handleImport = () => {
            importModel.importVisible = true;
        };
        const handleImportCancle = () => {
            importModel.importVisible = false;
        };
        const handleimportSubmit = () => {
            importModel.importVisible = false;
        };
        // 导出心跳
        const handlePaw = (item: any, type: string) => {
            // Freeze 冻结解冻 ResetPaw重置密码

            paw.pawTitle = '导出心跳表';
            paw.pawId = '0';
            paw.notesTitle = '注：为保数据安全，请输入密码导出报表';

            paw.type = '';
            paw.pawVisible = true;
            paw.pawLoading = false;
            console.log(paw);
        };
        // 导出心跳
        const handlePawCancle = () => {
            paw.pawVisible = false;
            paw.pawId = '';
            paw.type = '';
        };
        // 导出心跳
        const handlePawSubmit = () => {
            paw.pawVisible = false;
            paw.pawId = '';
        };

        // 导出设备
        const handDevice = () => {
            devShow.value = true;
        };
        // 导出设备
        const handDevCancle = () => {
            devShow.value = false;
        };
        // 导出设备
        const handDevSubmit = () => {
            devShow.value = false;
        };

        return {
            columns,
            ...toRefs(state),
            ...toRefs(importModel),
            ...toRefs(paw),

            columnsList,
            ...eslTables,
            userType,
            tableHeadFun,
            initFun,
            t,
            setRowKey,
            handleSelectQuery,
            handleInitQuery,
            handleCancle,
            handleSubmit,
            bindingShow,
            handBinding,
            handleBindingCancle,
            handleBindingSubmit,
            handleImport,
            handleImportCancle,
            handleimportSubmit,
            handlePaw,
            handlePawCancle,
            handlePawSubmit,
            handDevice,
            devShow,
            handDevCancle,
            handDevSubmit,
        };
    },
});
</script>

<style lang="scss" scoped>
.user {
    @include flex;
    width: 100%;
    &-dept {
        flex-basis: 200px;
        min-width: 200px;
    }
    &-data {
        flex: 1;
        padding-left: $width20;
        &__filter {
            @include flex;
        }
        &__table {
            padding: $width20 $width0;
            .multi-action {
                background: $white;
            }
            .action-btn {
                margin-right: $width8;
            }
        }
    }
}
</style>
